package com.etoak.rst.sys.dish.controller;

import cn.hutool.core.util.RandomUtil;
import com.etoak.rst.sys.dish.DTO.CategoryDTO;
import com.etoak.rst.sys.dish.DTO.DishDTO;
import com.etoak.rst.sys.dish.entity.Category;
import com.etoak.rst.sys.dish.entity.DIsh;
import com.etoak.rst.sys.dish.service.IDishService;
import com.etoak.rst.sys.util.JsonResponse;
import com.etoak.rst.sys.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;

import java.util.List;
import java.util.UUID;
import java.io.*;
@RestController
    @RequestMapping("/dish")
public class DishController {


    @Autowired
    private IDishService service;

    /* 菜品分页模糊查询
    * */
    @RequestMapping("/querySome")
    public JsonResponse querySome4Dish(DishDTO dto){
        List<DIsh> data = service.querySome4Dish(dto);
        PageInfo<DIsh> info = new PageInfo<>(data);
        return data.size()>0&&data!=null?
                    Result.success("200","success",info):
                    Result.failed("200021","failed","没有数据信息");
    }
    /* 菜品删除 (单个删除和多个删除)
    * */
    @RequestMapping("/delFoods")
    public JsonResponse delFoods(@RequestBody List<Integer> ids){
        try {
            service.delFoods(ids);
            return Result.success("200","success","删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failed("200031","failed","删除失败");
        }

    }
    /* 菜品添加
    * */
    @PostMapping("/addDish")
    public JsonResponse addDish(@RequestBody DIsh dIsh){
        boolean flag = service.addDish(dIsh);
        return flag?Result.success("200","success","添加成功"):
                Result.failed("200041","failed","添加失败");
    }
    /* 菜品修改
    * */

    @PostMapping("/pic")
    // SpringBoot 项目会通过 MultipartAutoConfiguration完成文件解析器的
    public JsonResponse pic(MultipartFile pic){

        // 旧名
        String originalFilename = pic.getOriginalFilename();
        // 拼接新名
        String pest = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newName = RandomUtil.randomString(16) + pest;
        // 存储到本地
        File direction = new File("d:\\taspics\\dishpic");
        if( !direction.exists() ){
            direction.mkdirs();
        }
        try {
            pic.transferTo(new File(direction,newName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 名字返回给前段
        return Result.success("/dishpic/"+newName);
    }



}
